/**
 * 订单本地存储工具
 */

const ORDER_STORAGE_KEY = 'pending_order_id';
const ORDER_TIME_KEY = 'pending_order_time';

/**
 * 保存待支付订单ID到本地存储
 * @param orderId 订单ID
 */
export const savePendingOrderId = (orderId: string): void => {
  try {
    localStorage.setItem(ORDER_STORAGE_KEY, orderId);
    localStorage.setItem(ORDER_TIME_KEY, Date.now().toString());
    console.log('订单ID已保存到本地存储:', orderId);
  } catch (error) {
    console.error('保存订单ID到本地存储失败:', error);
  }
};

/**
 * 获取待支付订单ID
 * @returns 订单ID或null
 */
export const getPendingOrderId = (): string | null => {
  try {
    const orderId = localStorage.getItem(ORDER_STORAGE_KEY);
    const orderTime = localStorage.getItem(ORDER_TIME_KEY);

    // 检查是否超时（20分钟）
    if (orderTime) {
      const timeDiff = Date.now() - parseInt(orderTime);
      const ORDER_TIMEOUT = 20 * 60 * 1000; // 20分钟

      if (timeDiff > ORDER_TIMEOUT) {
        console.log('订单已超时，清除本地存储');
        clearPendingOrderId();
        return null;
      }
    }

    console.log('从本地存储获取订单ID:', orderId);
    return orderId;
  } catch (error) {
    console.error('从本地存储获取订单ID失败:', error);
    return null;
  }
};

/**
 * 清除待支付订单ID
 */
export const clearPendingOrderId = (): void => {
  try {
    localStorage.removeItem(ORDER_STORAGE_KEY);
    localStorage.removeItem(ORDER_TIME_KEY);
    console.log('已清除本地存储的订单ID');
  } catch (error) {
    console.error('清除本地存储订单ID失败:', error);
  }
};

/**
 * 检查是否有待支付的订单
 * @returns 是否有待支付订单
 */
export const hasPendingOrder = (): boolean => {
  return getPendingOrderId() !== null;
};
